package com.nvwa.coding.model;


import com.nvwa.coding.util.safe.Coding;
import lombok.Getter;

import java.time.LocalDateTime;
import java.util.List;


public class StringDateTimePeriod extends AbstractDatePeriod<StringDateTime> {

    @Getter
    protected StringDateTime start;

    @Getter
    protected StringDateTime end;

    public static final StringDateTimePeriod EMPTY = new StringDateTimePeriod() {
        @Override
        public boolean valid() {
            return false;
        }
    };

    private StringDateTimePeriod() {

    }

    public StringDateTimePeriod(StringDateTime start, StringDateTime end) {
        this.start = start;
        this.end = end;
    }

    public StringDateTimePeriod(String start, String end) {
        this(new StringDateTime(start), new StringDateTime(end));
    }

    public static StringDateTimePeriod from(String period) {
        if (Coding.isBlank(period)) {
            return EMPTY;
        }
        List<String> split = Ensurer.ofSupplier(() -> Coding.arrayList("", ""), list -> list.size() == 2)
                                    .ensure(
                                            () -> Coding.splitToList(period, "-"),
                                            () -> Coding.splitToList(period, "_"),
                                            () -> Coding.splitToList(period, " "),
                                            () -> Coding.splitToList(period, "~"),
                                            () -> Coding.splitToList(period, ","),
                                            () -> Coding.splitToList(period, ";"),
                                            () -> Coding.splitToList(period, "|")
                                    );
        return new StringDateTimePeriod(split.get(0), split.get(1));
    }

    @Override
    public boolean inPeriod(StringDateTime o) {
        return inPeriod(o.asLocalDateTime());
    }

    public boolean inPeriod(LocalDateTime localDateTime) {
        if (localDateTime == null || notValid()) {
            return false;
        }
        return !start.asLocalDateTime().isAfter(localDateTime) && !end.asLocalDateTime().isBefore(localDateTime);
    }

    public boolean nowInPeriod() {
        return inPeriod(LocalDateTime.now());
    }

}
